package dragon.modules.system.file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import dragon.core.exception.ExceptionHandler;
import dragon.core.io.FileManager;
import dragon.core.io.FileManagerImp;
import dragon.core.io.LogicFile;
import dragon.core.io.ZipFiles;
import dragon.core.page.Page;
import dragon.core.util.FilePath;
import dragon.core.util.GlobalParameter;
import dragon.core.util.Handler;
import dragon.core.util.Reflect;
import dragon.core.util.StringUtils;
import ejw.ServerInterface.MultipartFormData;

public class FileHandler extends Handler {

	private static final Logger logger = LoggerFactory.getLogger(FileHandler.class);

	/**
	 * 文件管理实例
	 */
	FileManager fileManager = new FileManagerImp();

	/**
	 * 文件列表
	 * 
	 * @throws ExceptionHandler
	 */
	@SuppressWarnings("unchecked")
	public void list() throws ExceptionHandler {
		String path = getParameter("path");

		checkPath(path);

		StringBuilder strpath = new StringBuilder();
		strpath.append(FilePath.webRoot).append(path);
		List<LogicFile> files = fileManager.getLogicFiles(strpath.toString(), 0, false, false);
		strpath = null;
		path = null;

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(files.size());
		for (LogicFile lf : files) {
			list.add(Reflect.toMap(lf));
		}
		files = null;

		Page page = new Page();
		page.setResult(list);
		list = null;

		output(page.getJsonMapResult());
	}

	/**
	 * 创建目录
	 * 
	 * @throws ExceptionHandler
	 */
	@SuppressWarnings("unchecked")
	public void createFolder() throws ExceptionHandler {
		String path = getParameter("path");
		checkPath(path);
		String foldername = getParameter("foldername");
		StringBuilder strpath = new StringBuilder();
		strpath.append(FilePath.webRoot).append(path).append(FilePath.separator).append(foldername);
		boolean isExist = false;
		if (!fileManager.isFileExist(strpath.toString())) {
			fileManager.createFolder(strpath.toString());
		} else {
			isExist = true;
		}
		// StringBuilder msgStr = new StringBuilder();
		// msgStr.append("mt:FS|path:").append(path).append(FilePath.separator).append(foldername).append("|c:Create");
		// MessageServer.sendMessage(msgStr.toString());
		JSONObject result = new JSONObject();
		if (isExist) {
			result.put("MESSAGE_WARNING", "该文件夹已存在！");
		}
		output(result.toJSONString());
	}

	/**
	 * 保存(创建或修改)文件
	 * 
	 * @throws ExceptionHandler
	 */
	@SuppressWarnings("unchecked")
	public void saveFile() throws ExceptionHandler {
		String path = getParameter("path");
		checkPath(path);
		String action = getParameter("action");// create or modify
		String filename = getParameter("filename");
		String filecontent = getParameter("filecontent");

		StringBuilder filepath = new StringBuilder();
		filepath.append(FilePath.webRoot).append(path).append(FilePath.separator).append(filename);

		JSONObject result = new JSONObject();

		if ("create".equals(action)) {
			if (!fileManager.isFileExist(filepath.toString())) {
				fileManager.createFile(filepath.toString(), filecontent);
			} else {
				result.put("MESSAGE_WARNING", "该文件已存在！");
			}
		} else if ("modify".equals(action)) {
			if (fileManager.isFileExist(filepath.toString())) {
				fileManager.modifyFile(filepath.toString(), filecontent);
			} else {
				result.put("MESSAGE_WARNING", "待修改的文件不存在！文件路径：" + filepath.toString());
			}
		}

		// StringBuilder msgStr = new StringBuilder();
		// msgStr.append("mt:FS|path:").append(path).append(FilePath.separator).append(filename).append("|c:Create");
		// MessageServer.sendMessage(msgStr.toString());

		output(result.toJSONString());
	}

	/**
	 * 预修改文件
	 * 
	 * @throws ExceptionHandler
	 */
	public String preModFile() throws ExceptionHandler {
		String path = getParameter("path");
		checkPath(path);
		String filename = getParameter("filename");
		StringBuilder filepath = new StringBuilder();
		filepath.append(FilePath.webRoot).append(path).append(FilePath.separator).append(filename);

		String filecontent = fileManager.getFileContent(filepath.toString());
		setAttribute("filename", filename);
		setAttribute("filecontent", filecontent);

		filename = null;
		filecontent = null;
		filepath = null;

		return "/webmodules/file/editFile.jsp";
	}

	/**
	 * 目录或文件重命名
	 * 
	 * @throws ExceptionHandler
	 */
	@SuppressWarnings("unchecked")
	public void rename() throws ExceptionHandler {
		String path = getParameter("path");
		String oldname = getParameter("oldname");
		String newname = getParameter("newname");

		StringBuilder oldpath = new StringBuilder();
		oldpath.append(FilePath.webRoot).append(path).append(FilePath.separator).append(oldname);

		StringBuilder newpath = new StringBuilder();
		newpath.append(FilePath.webRoot).append(path).append(FilePath.separator).append(newname);

		JSONObject result = new JSONObject();

		if (!fileManager.isFileExist(newpath.toString())) {
			fileManager.renameFile(oldpath.toString(), newname);
		} else {
			result.put("MESSAGE_WARNING", "已存在同名的文件(夹)！");
		}
		// StringBuilder msgStr = new StringBuilder();
		// msgStr.append("mt:FS|path:").append(path).append(FilePath.separator).append(oldname).append("|c:Rename|NN:").append(newname);
		// MessageServer.sendMessage(msgStr.toString());

		output(result.toJSONString());
	}

	/**
	 * 目录或文件删除
	 * 
	 * @throws ExceptionHandler
	 */
	public void del() throws ExceptionHandler {
		String path = getParameter("path");
		checkPath(path);

		String filename = getParameter("filename");
		String[] filenames = filename.split(",");
		StringBuilder filepath = new StringBuilder();
		for (int i = 0; i < filenames.length; i++) {
			if (StringUtils.isEmpty(filenames[i])) {
				continue;
			}
			if (filepath.length() > 0) {
				filepath.delete(0, filepath.length());
			}
			filepath.append(FilePath.webRoot).append(path).append(FilePath.separator).append(filenames[i]);
			if (fileManager.isFileExist(filepath.toString())) {
				fileManager.deleteFile(filepath.toString());
			}
			// StringBuilder msgStr = new StringBuilder();
			// msgStr.append("mt:FS|path:").append(path).append(FilePath.separator).append(filenames[i]).append("|c:Delete");
			// MessageServer.sendMessage(msgStr.toString());
		}

		output(emptyJSON);
	}

	/**
	 * 目录或文件粘贴(执行复制或剪切操作)
	 * 
	 * @throws ExceptionHandler
	 */
	public void paste() throws ExceptionHandler {
		String target = getParameter("target");
		String optype = getParameter("optype");
		String sourcefile = getParameter("sourcefiles");
		String[] sourcefiles = sourcefile.split(",");

		StringBuilder sourcepath = new StringBuilder();
		StringBuilder targetpath = new StringBuilder();

		for (String source : sourcefiles) {
			if (sourcepath.length() > 0) {
				sourcepath.delete(0, sourcepath.length());
			}
			if (targetpath.length() > 0) {
				targetpath.delete(0, targetpath.length());
			}

			sourcepath.append(FilePath.webRoot).append(source);
			targetpath.append(FilePath.webRoot).append(target);

			if ("cut".equals(optype)) {
				// 剪切
				fileManager.moveFile(sourcepath.toString(), targetpath.toString());
			} else {
				// 复制
				fileManager.copyFile(sourcepath.toString(), targetpath.toString());
			}
		}

		output(emptyJSON);
	}

	/**
	 * 上传文件
	 * 
	 * @throws ExceptionHandler
	 */
	public void upload() throws ExceptionHandler {
		String path = getParameter("path");
		String index = getParameter("index");
		String[] ids = index.split(",");

		MultipartFormData data = null;
		StringBuilder filepath = new StringBuilder();
		for (String id : ids) {
			if (filepath.length() > 0) {
				filepath.delete(0, filepath.length());
			}
			data = getServerInterface().getMultipartFormData("file" + id);
			filepath.append(FilePath.webRoot).append(path).append(FilePath.separator).append(data.getName());
			data.getStoredLocation().renameTo(new File(filepath.toString()));

			// 如果是自定义的压缩包文件，需要解压到当前目录
			if (filepath.toString().endsWith(GlobalParameter.CompressedFilePostfix)) {
				File file = new File(filepath.toString());
				String unZipSource = file.getAbsolutePath();
				String unZipTarget = file.getParentFile().getParent() + FilePath.separator;
				ZipFiles.unZip(unZipSource, unZipTarget);
				// file.delete();// 删除压缩包
			}
		}

		output(emptyJSON);
	}

	/**
	 * 打包文件
	 * 
	 * @return
	 * @throws ExceptionHandler
	 */
	public void zip() throws ExceptionHandler {
		String path = getParameter("path");
		checkPath(path);

		String source = FilePath.webRoot + path;
		String target;
		if ("".equals(path)) {
			target = source + "all" + GlobalParameter.CompressedFilePostfix;
		} else {
			target = source + FilePath.separator + path.substring(path.lastIndexOf(FilePath.separator) + 1) + GlobalParameter.CompressedFilePostfix;
		}

		ZipFiles.zip(source, target);

		output(emptyJSON);
	}

	/**
	 * 对请求操作的路径进行校验
	 * 
	 * @param path
	 *            文件路径
	 * @throws ExceptionHandler
	 */
	private void checkPath(String path) throws ExceptionHandler {
		// TODO:入口路径检查
		// if (!(path.startsWith("t") || path.startsWith("ad") || path.startsWith("res"))) {
		// throw new ExceptionHandler("非法路径！");
		// }
	}

	/**
	 * KindEditor 附件上传(flash,image,file,media)
	 * 
	 * @throws ExceptionHandler
	 */
	public void kindEditorUpload() throws ExceptionHandler {

		Map<String, String> map = getParameterMap();

		String filetype = getParameter("dir");// dir: 上传类型，分别为image、flash、media、file

		int error = 1;
		String path = map.get("imgFile");
		String savepath = null;// 文件存储路径
		if (!StringUtils.isEmpty(path)) {
			String[] paths = path.split(":");
			if (paths.length == 2) {
				error = 0;
				savepath = paths[0];
			}
		}
		map = null;

		JSONObject result = new JSONObject();
		result.put("error", error);
		if (error == 0) {
			if ("file".equals(filetype)) {
				result.put("url", getBasePath() + "dragon/model/action/BizObjectHandler/getFile.ejw?path=" + path);
			} else {
				result.put("url", getBasePath() + "data/upload/" + savepath);
			}
		} else {
			result.put("message", path);
		}

		output(result.toJSONString());

		result = null;
	}

}
